package com.yang.yangmusic.controller;

import com.yang.yangmusic.dto.UserCreateRequest;
import com.yang.yangmusic.dto.UserUpdateRequest;
import com.yang.yangmusic.mapper.UserMapper;
import com.yang.yangmusic.service.UserService;
import com.yang.yangmusic.vo.UserVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther:zhaoyangyang
 * @Date:2022/1/7-01-07-13:36
 * @Description:com.yang.yangmusic.controller
 * @version:1.0
 */
@RestController
@RequestMapping("/users")
@CrossOrigin
public class UserController {

   UserService userService;
   UserMapper userMapper ;

   @GetMapping("/hello")
   public String sayHello(){
      return "hello";
   }
   @GetMapping("/")
   Page<UserVo> search(@PageableDefault(sort = {"createdTime"}, direction = Sort.Direction.ASC) Pageable pageable){
      return userService.search(pageable)
              .map(userMapper::toVo);
   }

   @PostMapping("/")
   UserVo create(@Validated @RequestBody UserCreateRequest userCreateRequest) {
      return userMapper.toVo(userService.create(userCreateRequest));
   }
   @GetMapping("/{id}")
   UserVo get(@PathVariable String id){
      return userMapper.toVo(userService.get(id));
   }
   @PutMapping("/{id}")
   UserVo update( @PathVariable String id,@Validated @RequestBody UserUpdateRequest userUpdateRequest){
    return  userMapper.toVo(userService.update(id,userUpdateRequest));
   }
   @DeleteMapping("/{id}")
   void delete(@PathVariable String id){
      userService.delete(id);
   }
   @Autowired
   public void setMapper(UserMapper userMapper){
      this.userMapper = userMapper;
   }
   @Autowired
   public void setUserService(UserService userService) {
      this.userService = userService;
   }
}
